package com.rookie.redis.module.config;

import com.rookie.redis.module.annotation.DetectRepeat;
import com.rookie.redis.module.util.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author rookie
 */
@Aspect
@Component
public class RepeatAspect {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 切点
     *
     * @param detectRepeat 注解
     */
    @Pointcut("@annotation(detectRepeat)")
    public void controllerCut(DetectRepeat detectRepeat) {
    }

    @Around(value = "controllerCut(detectRepeat)", argNames = "joinPoint,detectRepeat")
    public Object doAround(ProceedingJoinPoint joinPoint, DetectRepeat detectRepeat) throws Throwable {

        Object[] args = joinPoint.getArgs();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new RuntimeException("请求异常");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authentication");
        String path = request.getServletPath();
        if (!StringUtils.hasText(token)) {
            throw new RuntimeException("请求异常");
        }
        if (getRequestToken(token,path)){
            throw new RuntimeException("重复请求");
        }
        setRequestToken(token,path);

        Object proceed;
        try {
            proceed = joinPoint.proceed(args);
        } finally {
            removeRequestToken(token,path);
        }

        return proceed;
    }

    private boolean getRequestToken(String token, String path) {
        return redisUtils.hasKey(token + path);
    }
    private void setRequestToken(String token, String path){
        redisUtils.set(token + path,1);
    }

    private void removeRequestToken(String token, String path){
        redisUtils.del(token + path);
    }
}
